import { RouteRecordRaw, createRouter, createWebHistory, RouterOptions } from 'vue-router'

const routes: Array<RouteRecordRaw> = [
  {
    path: '/',
    name: 'Layout',
    meta: { requiresAuth: true },
    redirect: '/home',
    component: () => import('../views/basis/layout/index.vue'),
    children: [
      {
        path: '/home',
        name: 'Home',
        component: () => import('../views/home/index.vue')
      },
      {
        path: '/applicationCenter',
        name: 'ApplicationCenter',
        component: () => import('../views/applicationCenter/index.vue')
      },
      {
        path: '/personalCenter/information',
        name: 'PersonalCenter/information',
        component: () => import('../views/personalCenter/information/index.vue')
      },
      {
        path: '/personalCenter/attendance',
        name: 'PersonalCenter/attendance',
        component: () => import('../views/personalCenter/attendance/index.vue')
      },
      {
        path: '/personalCenter/salary',
        name: 'PersonalCenter/salary',
        component: () => import('../views/personalCenter/salary/index.vue')
      },
      {
        path: '/regimeCenter',
        name: 'RegimeCenter',
        component: () => import('../views/regimeCenter/index.vue')
      },
      {
        path: '/systemConfig/organization',
        name: 'SystemConfig/organization',
        component: () => import('../views/systemConfig/organization/index.vue')
      },
      {
        path: '/systemConfig/employees',
        name: 'SystemConfig/employees',
        component: () => import('../views/systemConfig/employees/index.vue')
      },
      {
        path: '/systemConfig/role',
        name: 'SystemConfig/role',
        component: () => import('../views/systemConfig/role/index.vue')
      },
      {
        path: '/systemConfig/department',
        name: 'SystemConfig/department',
        component: () => import('../views/systemConfig/department/index.vue')
      },
      {
        path: '/systemConfig/menu',
        name: 'SystemConfig/menu',
        component: () => import('../views/systemConfig/menu/index.vue')
      },
      {
        path: '/systemConfig/dictionary',
        name: 'SystemConfig/dictionary',
        component: () => import('../views/systemConfig/dictionary/index.vue')
      }
    ]
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import('../views/basis/login/index.vue')
  },
  {
    path: '/:pathMatch(.*)',
    component: () => import('../views/basis/layout/index.vue')
  }
]

export const router = createRouter({
  history: createWebHistory(),
  routes,
  scrollBehavior(to: any, from: any) {
    if (to.path !== from.path) {
      return { top: 0 }
    }
  }
} as RouterOptions)

router.beforeEach((to, from, next) => {
  const token: string = window.sessionStorage.getItem('token') || ''
  if (to.name !== 'Login' && to.meta.requiresAuth && !token) next({ name: 'Login' })
  else next()
})
